<template>
  <div class="dashboard-editor-container">
    <div style="display: flex;justify-content: center;margin-top: 10px">









    </div>

    <div id="container"></div>
  </div>
</template>

<script>


import {getMuseum} from "@/api/project/museum";

let myweizhi = ""


export default {
  name: 'Index',
  components: {},
  data() {
    return {
      start: '',
      end: '',
      //116.38,39.91
      myLat:39.91,
      myLon:116.38,
      geolocation: '',
      marker: {},
      map: '',
      data:{},
      center: '',
      polylineLayer: {},
      infoWindow: '',
      centerDialogVisible: false,
      fangshi:'自驾'
    }
  },
  mounted() {

    this.myLat = this.$route.query.myLon
    this.myLon = this.$route.query.myLat
    this.geolocation = new qq.maps.Geolocation("G6EBZ-QDXCQ-XEX5O-B324L-USHWQ-34BY5", "myapp");

    this.geolocation.getLocation(this.showPosition, this.showErr);


    this.center = new window.TMap.LatLng(this.myLat,this.myLon )
//定义map变量，调用 TMap.Map() 构造函数创建地图
    this.map = new window.TMap.Map(document.getElementById('container'), {
      center: this.center,//设置地图中心点坐标
      zoom: 17.2,   //设置地图缩放级别
      pitch: 43.5,  //设置俯仰角
      rotation: 45    //设置地图旋转角度
    });
    this.marker = new window.TMap.MultiMarker({
      map: this.map,  //指定地图容器


      geometries: [],


    });


    this.polylineLayer = new window.TMap.MultiPolyline({
      id: 'polyline-layer', //图层唯一标识
      map: this.map,//绘制到目标地图
      //折线样式定义
      styles: {
        'style_blue': new TMap.PolylineStyle({
          'color': '#3777FF', //线填充色
          'width': 6, //折线宽度
          'borderWidth': 5, //边线宽度
          'borderColor': '#FFF', //边线颜色
          'lineCap': 'butt' //线端头方式
        }),
      },

      //折线数据定义
      geometries: []
    })

        getMuseum({
          id:this.$route.query.id
        }).then(res=>{
          this.data=res.data
          this.marker.add([{
            "id": 1,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
            styles: {
              // 点标记样式
              marker: new TMap.MarkerStyle({
                width: 20, // 样式宽
                height: 30, // 样式高
                anchor: { x: 10, y: 30 }, // 描点位置
              }),
            },
            "position": new window.TMap.LatLng(this.myLat, this.myLon),  //点标记坐标位置
            "properties": {//自定义属性

              "name": this.data.name,
              "coordinate": this.data.coordinate,
              "address": this.data.address,
              "content": this.data.content,
              "pic": this.data.pic,
              "price": this.data.price,



            }
          }])

          var infoWindow = new window.TMap.InfoWindow({
            map: this.map,
            position: new window.TMap.LatLng(39.984104,116.307503),
            content: "<div><p>Hello World!</p></div>",
            offset: { x: 0, y: -32 } //设置信息窗相对position偏移像素，为了使其显示在Marker的上方

          });

          infoWindow.close();//初始关闭信息窗关闭
let that =this
          this.marker.on("click", function (evt) {
            console.log('111');
            console.log("evt.geometry", evt.geometry.properties);
            // 设置infoWindow
            that.infoWindow.open(); // 打开信息窗
            that.infoWindow.setPosition(evt.geometry.position); // 设置信息窗位置
               let xxx="<div style='display: flex;font-size: 16px;line-height: 16px'><p>名字:</p><p>"+evt.geometry.properties.name+"</p></div>" +
                   "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>坐标:</p><p>"+evt.geometry.properties.coordinate+"</p></div>" +
                   "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>地址:</p><p>"+evt.geometry.properties.address+"</p></div>" +
                   "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>价格:</p><p>"+evt.geometry.properties.price+"</p></div>" +
                   "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px; text-overflow: ellipsis;'><p>介绍:</p><p  style='width: 160px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>"+evt.geometry.properties.content+"</p></div>" +
                   "<div style='display: flex;'><img width='350px' height='200px' src="+evt.geometry.properties.pic.split(',')[0]+"></div>"

            that.infoWindow.setContent(xxx); // 设置信息窗内容

          })
        })



   // this.marker.on("click", function (evt) {
   //    console.log('111')
   //    console.log("evt.geometry",evt.geometry.properties)
   //    //设置infoWindow
   //    infoWindow.open(); //打开信息窗
   //    infoWindow.setPosition(evt.geometry.position);//设置信息窗位置
   //    let xxx="<div style='display: flex;font-size: 16px;line-height: 16px'><p>名字:</p><p>"+evt.geometry.properties.name+"</p></div>" +
   //        // "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>编码:</p><p>"+evt.geometry.properties.idid+"</p></div>" +
   //        // "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>类型:</p><p>"+evt.geometry.properties.leixing+"</p></div>" +
   //        // "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>功率:</p><p>"+evt.geometry.properties.gonglv+"</p></div>" +
   //        // "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>电池:</p><p>"+evt.geometry.properties.dianchi+"</p></div>" +
   //        // "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>介绍:</p><p>"+evt.geometry.properties.info+"</p></div>" +
   //        //
   //        // "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>地址:</p><p>"+evt.geometry.properties.address+"</p></div>" +
   //        //
   //        // "<div style='display: flex;margin-top: -30px;font-size: 16px;line-height: 16px'><p>时价:</p><p>"+evt.geometry.properties.shijia+"</p></div>"+
   //        "<div style='display: flex;'><img width='350px' height='200px' src="+evt.geometry.properties.pic+"></div>"
   //
   //    infoWindow.setContent(xxx);//设置信息窗内容
   //
   //
   //  })


    console.log("--------------", this.polylineLayer)


    this.infoWindow = new window.TMap.InfoWindow({
      map: this.map,
      /*      39.984104,116.307503
            22.688769,113.991176
            */
      position: new window.TMap.LatLng(this.myLat,this.myLon),
      content: "<div><p>Hello World!</p></div>",
      offset: {x: 0, y: -32} //设置信息窗相对position偏移像素，为了使其显示在Marker的上方

    });
    this.infoWindow.close();//初始关闭信息窗关闭


    window.cb = function (ret) {
      //从结果中取出路线坐标串
      console.log("aaaaaaa", ret)
      var coors = ret.result.routes[0].polyline, pl = [];
      //坐标解压（返回的点串坐标，通过前向差分进行压缩，因此需要解压）
      var kr = 1000000;
      for (var i = 2; i < coors.length; i++) {
        coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
      }
      //将解压后的坐标生成LatLng数组
      for (var i = 0; i < coors.length; i += 2) {
        pl.push(new window.TMap.LatLng(coors[i], coors[i + 1]));
      }
      window.display_polyline(pl)//显示路线

    }


    window.display_polyline = (pl) => {
      this.polylineLayer.updateGeometries({
        'id': 'pl_1',
        'styleId': 'style_red',
        'paths': pl
      })
    }
    /*  window.display_polyline = function (pl) {
        //创建 MultiPolyline显示折线
        console.log("画线")
        // updateGeometries
        this.polylineLayer.updateGeometries({//新的折线添加到图层中
          'id': 'pl_1',
          'styleId': 'style_red',
          'paths': pl
        })


      }*/


  },

  methods: {
    //计算二者之间的距离

    haversineDistance(lat1, lon1, lat2, lon2, R = 6371e3) { // R默认为地球半径，单位为米
      const rad = (d) => d * Math.PI / 180; // 角度转弧度

      const dLat = rad(lat2 - lat1);
      const dLon = rad(lon2 - lon1);
      const a =
          Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(rad(lat1)) * Math.cos(rad(lat2)) *
          Math.sin(dLon / 2) * Math.sin(dLon / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

      return R * c; // 距离，单位为米
    },
    get() {
      let start = this.start.split(",")[1] + "," + this.start.split(",")[0]
      let end = this.end.split(",")[1] + "," + this.end.split(",")[0]
      var url = "https://apis.map.qq.com/ws/direction/v1/driving/"; //请求路径
      url += "?from=" + start;  //起点坐标
      // url+="&to=111.47,27.24";  //终点坐标
      url += "&to=" + end

      url += "&output=jsonp&callback=cb";  //指定JSONP回调函数名，本例为cb
      url += "&key=G6EBZ-QDXCQ-XEX5O-B324L-USHWQ-34BY5"; //开发key，可在控制台自助创建
      console.log(url)
      this.jsonp_request(url)
      console.log("坐标",this.start.split(",")[1],this.start.split(",")[0],this.end.split(",")[1],this.end.split(",")[0])
      let line=this.haversineDistance(this.start.split(",")[1],this.start.split(",")[0],this.end.split(",")[1],this.end.split(",")[0])

      this.myLat=this.start.split(",")[0]
      this.myLon=this.start.split(",")[1]

      if (this.fangshi=='自驾'){
        this.$notify({
          title: '提示',
          message: '全程'+(line.toFixed(2)/1000).toFixed(1)+"公里，开车匀速40/km大概需要"+(line.toFixed(2)/1000/40).toFixed(1)+"小时",
          duration: 0
        });
      }else if (this.fangshi=='公交'){
        this.$notify({
          title: '提示',
          message: '全程'+(line.toFixed(2)/1000).toFixed(1)+"公里，公交匀速30/km大概需要"+(line.toFixed(2)/1000/30).toFixed(1)+"小时",
          duration: 0
        });
      }else if (this.fangshi=='步行'){
        this.$notify({
          title: '提示',
          message: '全程'+(line.toFixed(2)/1000).toFixed(1)+"公里，步行匀速15/km大概需要"+(line.toFixed(2)/1000/15).toFixed(1)+"小时",
          duration: 0
        });
      }




      this.map.panTo(new window.TMap.LatLng(this.start.split(",")[1],  this.start.split(",")[0]))




    },


// 定位成功之后调用的方法

    showPosition(position) {

      let lat = position.lat;

      let lng = position.lng;

      console.log(lat);
      console.log(lng);

      myweizhi = lat + "," + lng

      // console.log("获取当前定位成功------------------------", myweizhi)
      // Notification.success("获取当前定位成功------------------------(" + lat + "," + lng + ")！")
    },

    showErr() {

      console.log('定位失败');

    },


//创建并初始化MultiMarker


//浏览器调用WebServiceAPI需要通过Jsonp的方式，此处定义了发送JOSNP请求的函数
    jsonp_request(url) {

      var script = document.createElement('script');
      script.src = url;
      document.body.appendChild(script);
    },

//定义请求回调函数

  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  .title {
    font-size: 50px;
    color: #409EFF;
    text-align: center;
    font-family: '宋体';
    font-weight: bold;
  }

  // padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
